import struct
import random
import numpy as np

def fp32_to_hex(f):
    """将FP32数值转换为16进制字符串"""
    if isinstance(f, int):
        return f"{f:08X}"
    return f"{np.uint32(f.view(np.uint32)):08X}"

def generate_fp32_case():
    """生成单个FP32测试用例"""
    num_type = random.choice(["normal", "normal", "denormal", "zero", "inf"])
    
    sign = random.choice([0, 1])
    
    if num_type == "zero":
        return (sign << 31) | 0x00000000
    elif num_type == "inf":
        return (sign << 31) | 0x7F800000
    elif num_type == "denormal":
        mantissa = random.randint(1, 0x007FFFFF)
        return (sign << 31) | mantissa
    else:  # normal
        exp = random.randint(1, 0xFE)  # 1-254
        mantissa = random.randint(0, 0x007FFFFF)
        return (sign << 31) | (exp << 23) | mantissa

def fp32_add(a, b):
    """使用NumPy的FP32加法并处理特殊NaN情况"""
    np_a = np.uint32(a).view(np.float32)
    np_b = np.uint32(b).view(np.float32)
    sum_val = np_a + np_b
    
    # 统一NaN表示为静默NaN 0x7FC00000
    if np.isnan(sum_val):
        return 0x7FC00000
    return np.uint32(sum_val.view(np.uint32))

# 生成测试用例
test_cases = []
for _ in range(100):
    a = generate_fp32_case()
    b = generate_fp32_case()
    expected = fp32_add(a, b)
    
    test_cases.append({
        "a": fp32_to_hex(a),
        "b": fp32_to_hex(b),
        "expected": fp32_to_hex(expected)
    })

# 输出到文件
with open("fp32_add_cases.txt", "w") as f:
    f.write("// FP32加法测试用例（输入A，输入B，预期结果）\n")
    for case in test_cases:
        f.write(f"{case['a']} {case['b']} {case['expected']}\n")

print("生成100个测试用例到fp32_add_cases.txt")